/**
 * A simple sleep utility using <windows.h> Sleep(long milliseconds) function
 * by Xia Zuoling
 * Date: 10:22:53 2006-12-1
 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <errno.h>
#include <windows.h>
#include <stdarg.h>

/* static variables */
static const char *bname;

const char *basename(char *argv0)
{
    const char *p;
    if (argv0 == 0) return 0;
    p = strrchr(argv0, '/');
    if (p) return p + 1;
    p = strrchr(argv0, '\\');
    if (p) return p + 1;
    return argv0;
}

int error(int status, const char *format, ...)
{
    va_list va;
    va_start(va, format);
    fprintf(stderr, "%s: error: ", bname);
    vfprintf(stderr, format, va);
    if (status)
        exit(status);
    va_end(va);
    return 0;
}

long get_number(const char *str)
{
    long n;
    char *ptr;
    n = strtol(str, &ptr, 0);
    if (errno == ERANGE)
        error(-1, "%s: out of range.\n", str);
    if (ptr == str)
        error(-1, "%s: invalid number.\n", str);
    return n;
}

int main(int argc, char *argv[])
{
    long sec, msec;
    sec = 0;
    msec = 0;
    /* initialization */
    bname = basename(argv[0]);
    /* ----  program  ---- */
    if (argc < 2)
    {
        error(1, "\nusage: %s [seconds] [milliseconds]\n   or: %s [milliseconds]\n",
            bname, bname);
    }
    if (argc == 2) /* only one number given, treat as milliseconds */
    {
        msec = get_number(argv[1]);
    }
    else
    {
        sec = get_number(argv[1]);
        msec = get_number(argv[2]);
    }
    Sleep(sec * 1000 + msec);
    return 0;
}
